package com.webserver.controller;

import com.webserver.core.DispatcherServlet;
import com.webserver.entity.Article;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.URISyntaxException;

/**
 * @author 马强
 * @Description 处理文章
 * @create 2022-04-15 8:35
 */
public class ArticleController {
    private static File userDir;
    private static File root;
    private static File staticDir;
    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        userDir = new File("./articles");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
         String title = request.getParameter("title");
         String author= request.getParameter("author");
         String content = request.getParameter("content");


         //如果标题或内容没有输入则响应发表失败页面
        System.out.println(title+"----------------------"+content);
        if(title == null || content == null){

            File file = new File(staticDir, "/myweb/article_fail.html");
            response.setContentFile(file);
            return;
        }
        File userFile = new File(userDir,title+".obj");

       try(
           FileOutputStream fos = new FileOutputStream(userFile);
           ObjectOutputStream oos = new ObjectOutputStream(fos);
       ){
           Article article = new Article(title,author,content);
           oos.writeObject(article);
           //发表成功了
           File file = new File(staticDir,"/myweb/article_success.html");
           response.setContentFile(file);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }



    }
}
